<?php

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;
use Co;

class Swoole1 extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('swoole1')
            ->setDescription('the test command');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $this->serv = new \Swoole\Server("127.0.0.1", 9501);

        $this->serv->set(array(
            'worker_num' => 2, //一般设置为服务器CPU数的1-4倍
            'daemonize' => 0, //以守护进程执行
            'task_worker_num' => 8, //task进程的数量
            "log_file" => "swoolw_task.log" ,//日志
        ));
        $this->serv->on('Receive', array($this, 'onReceive'));
        $this->serv->on('Task', array($this, 'onTask'));
        $this->serv->on('Finish', array($this, 'onFinish'));
        $this->serv->start();

    }


    //接收客户端的请求并响应
    public function onReceive($serv, $fd, $from_id, $data){
        file_put_contents(__DIR__.'/swoole1.log','--------------------------------------'."\r\n",FILE_APPEND);
        file_put_contents(__DIR__.'/swoole1.log','请求时间：'.time()."\r\n",FILE_APPEND);
        $serv->send($fd, "SUCCESS");//返回信息给客户端

        $serv->task($data);//投递任务


    }

    public function onTask($serv, \Swoole\Server\Task $task){
        file_put_contents(__DIR__.'/swoole1.log','任务开始时间：'.time()."\r\n",FILE_APPEND);
        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);
        //来自哪个 Worker 进程
        $task->worker_id;
        //任务的编号
        $task->id;
        //任务的类型，taskwait, task, taskCo, taskWaitMulti 可能使用不同的 flags
        $task->flags;
        //任务的数据
        $task->data;
        $order = Db::table('fa_yuewen_order_copy')->where('id',1)->find();
        unset($order['id']);
        $num = $redis->LLEN($task->data);
        for($i=0;$i<$num;$i++){
            $order_num = $redis->rPop( $task->data);
            go(function () use($order_num){
                if($order_num){
                    $order['order_number'] = $order_num ;
                    Db::table('fa_yuewen_order_copy')->insert($order);
                }
            });
        }

        file_put_contents(__DIR__.'/swoole1.log','任务结束时间：'.time()."\r\n",FILE_APPEND);
        return  $task->data;
    }

    //任务执行完自动回调结束方法
    public function onFinish($serv, $task_id, $data)
    {

        file_put_contents(__DIR__.'/swoole1.log','任务回调时间：'.time()."\r\n",FILE_APPEND);
        return true;
    }













}
